package com.Jian.reggie.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * ClassName: GlobalExceptionHandler
 * Package: com.Jian.reggie.common
 * Description:
 *
 * @Author 蹇泽阳
 * @Create 2023/11/25 16:15
 * @Version 1.0
 */
// @RestControllerAdvice是一个组合注解
// 由 @ControllerAdvice、@ResponseBody组成
// @ControllerAdvice继承了@Component
// 因此@RestControllerAdvice本质上是个Component，用于定义@ExceptionHandler，@InitBinder和@ModelAttribute方法，适用于所有使用@RequestMapping方法。
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
  // 当重复添加员工时候，抛出SQLIntegrityConstraintViolationException异常，所以要捕获这个异常
  @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
  @ResponseBody
  public R exceptionHandler(SQLIntegrityConstraintViolationException ex) {
    log.error(ex.getMessage());// Duplicate entry '1264667566' for key 'employee.idx_username'
    if (ex.getMessage().contains("Duplicate entry")) {
      String username = ex.getMessage().split(" ")[2];
      return R.error(username + "已存在");
    }
    
    return R.error("未知错误");
  }
  
  // 处理业务异常
  @ExceptionHandler(CustomException.class)
  @ResponseBody
  public R exceptionHandler(CustomException ex) {
    log.error(ex.getMessage());
    return R.error(ex.getMessage());
  }
 
}
